<script setup lang="ts">
import { h, ref, reactive, onMounted } from 'vue'
import { NModal, NCard, NForm, NFormItem, NInput, NSelect, NButton, NDataTable, NPagination, useNotification } from 'naive-ui'
import type { DataTableColumns, DataTableRowKey } from 'naive-ui'
import http from '@/tools/http'

import { useDictStore } from '@/stores/dictStore'
import { useUserStore } from '@/stores/userStore'
import { useConfigStore } from '@/stores/configStore'

const notification = useNotification()
const dictStore = useDictStore()
const userStore = useUserStore()
const configStore = useConfigStore()

type RowData = {
    userId: string
    messageId: string
    messageTitle: string
    messageContent?: string
    messageStatus?: string
    messageCreator?: string
    createTime?: string
    completeTime?: string
}

const userMessageTableColumns: DataTableColumns<RowData> = [
    {
        type: 'selection'
    }, {
        title: "消息标题",
        key: "messageTitle",
        width: 170,
        render(rowData: RowData, rowIndex: number) {
            return h(
                NButton,
                {
                    quaternary: true,
                    color: configStore.getThemeColor(),
                    onClick: () => openUserMessage(rowData)
                },
                () => rowData.messageTitle
            )
        }
    }, {
        title: "消息状态",
        key: "messageStatus",
        width: 100,
        render(rowData: RowData, rowIndex: number) {
            return dictStore.dictItem("USER_MESSAGE_STATUS", rowData.messageStatus)
        }
    }, {
        title: "消息发送人",
        key: "messageCreator",
        width: 100
    }, {
        title: "创建时间",
        key: "createTime",
        width: 160
    }, {
        title: "完成时间",
        key: "completeTime",
        width: 160
    }
]

const userMessageData = reactive<any>({
    list: [],
    pageNum: 1,
    pageSize: 10,
    pages: 1,
    total: 0
})

const userMessageSearchFormValue = reactive({
    pageNum: 1,
    pageSize: 10,
    userId: "",
    messageTitle: "",
    messageStatus: undefined,
    messageCreator: ""
})

const checkedRowKeysRef = ref<string[]>([])
const visiable = ref<boolean>(false)
const title = ref<string>("")
const formData = reactive<RowData>({
    userId: "",
    messageId: "",
    messageTitle: "",
    messageContent: "",
    messageStatus: "",
    messageCreator: "",
    createTime: "",
    completeTime: ""
})

onMounted(() => {
    userMessageSearchFormValue.userId = userStore.account
    pageUserMessage()
})

function handleCheck(rowKeys: DataTableRowKey[]) {
    checkedRowKeysRef.value = rowKeys as string[]
}

function pageNumChange(pageNum: number) {
    userMessageSearchFormValue.pageNum = pageNum
    pageUserMessage()
}

function pageSizeChange(pageSize: number) {
    userMessageSearchFormValue.pageSize = pageSize
    pageUserMessage()
}

function openUserMessage(row: RowData) {
    visiable.value = true
    title.value = row.messageTitle
    formData.userId = row.userId
    formData.messageId = row.messageId
    formData.messageTitle = row.messageTitle
    formData.messageContent = row.messageContent
    formData.messageStatus = row.messageStatus
    formData.messageCreator = row.messageCreator
    formData.createTime = row.createTime
    formData.completeTime = row.completeTime
    checkedRowKeysRef.value.length = 0
    checkedRowKeysRef.value.push(row.userId + "_" + row.messageId)
    completeUserMessage()
}

function pageUserMessage() {
    http.post("/user/message/page", userMessageSearchFormValue).then(({ data }) => {
        if (data.code === "0") {
            userMessageData.pageNum = data.data.pageNum
            userMessageData.pageSize = data.data.pageSize
            userMessageData.pages = data.data.pages
            userMessageData.total = data.data.total
            userMessageData.list.length = 0
            for (let i = 0; i < data.data.list.length; i++) {
                userMessageData.list.push(data.data.list[i])
            }
        }
    })
}

function completeUserMessage() {
    const request = []
    for (let i = 0; i < checkedRowKeysRef.value.length; i++) {
        const arr = checkedRowKeysRef.value[i].split('_')
        const temp = {
            userId: arr[0],
            messageId: arr[1]
        }
        request.push(temp)
    }
    if (request.length !== 0) {
        http.post("/user/message/complete", request).then(({ data }) => {
            if (data.code === "0") {
                checkedRowKeysRef.value.length = 0
                pageUserMessage()
                userStore.countUserMessage()
            }
        })
    }
}
</script>

<template>
    <div id="flame-container">
        <div class="search">
            <n-form :model="userMessageSearchFormValue" inline label-placement="left">
                <n-form-item label="消息标题" path="messageTitle">
                    <n-input v-model:value="userMessageSearchFormValue.messageTitle" placeholder="请输入消息标题" clearable />
                </n-form-item>
                <n-form-item label="消息状态" path="messageStatus">
                    <n-select style="width:216px" v-model:value="userMessageSearchFormValue.messageStatus"
                        :options="dictStore.dict('USER_MESSAGE_STATUS')" placeholder="请选择消息状态" clearable />
                </n-form-item>
                <n-form-item label="消息发起人" path="messageCreator">
                    <n-input v-model:value="userMessageSearchFormValue.messageCreator" placeholder="请输入消息发起人" clearable />
                </n-form-item>
                <n-form-item>
                    <n-button attr-type="button" @click="pageUserMessage()">查询</n-button>
                </n-form-item>
            </n-form>
        </div>
        <div class="btn-group">
            <n-button :disabled="checkedRowKeysRef.length === 0" attr-type="button"
                @click="completeUserMessage()">标记已读</n-button>
        </div>
        <div class="data-table">
            <n-data-table :scroll-x="690" :scrollbar-props="{ trigger: 'none' }" style="height:100%" flex-height
                :row-key="(row: RowData) => row.userId + '_' + row.messageId" :columns="userMessageTableColumns"
                :data="userMessageData.list" :bordered="false" @update:checked-row-keys="handleCheck" />
        </div>
        <div class="pagination">
            <n-pagination style="float:right" v-model:page="userMessageData.pageNum" :page-size="userMessageData.pageSize"
                :item-count="userMessageData.total" :page-sizes="[5, 10, 30, 50, 100]" :on-update-page="pageNumChange"
                :on-update-page-size="pageSizeChange" show-quick-jumper show-size-picker />
        </div>
    </div>
    <n-modal v-model:show="visiable">
        <n-card style="width:50%;height:300px" :title="title" closable @close="visiable = false">
            {{ formData.messageContent }}
        </n-card>
    </n-modal>
</template>

<style scoped>
</style>